﻿// FileNameConv.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

int FileNameConvert(const TCHAR *dir, int CodePage)
{
	int result = 0;
	TCHAR filter[MAX_PATH];
	_tcscpy(filter, dir);
	_tcscat(filter, _T("\\*.*"));

	WIN32_FIND_DATA FindData;

	HANDLE hFind = ::FindFirstFile(filter, &FindData);

	if (INVALID_HANDLE_VALUE == hFind)
		return -1;

	while(true)
	{
		if (_tcscmp(FindData.cFileName, _T(".")) && _tcscmp(FindData.cFileName, _T("..")))
		{
			TCHAR filename[MAX_PATH];
			_tcscpy(filename, dir);
			_tcscat(filename, _T("\\"));
			_tcscat(filename, FindData.cFileName);

			char aFileName[MAX_PATH];
			WideCharToMultiByte(CodePage, 0, FindData.cFileName, -1, aFileName, MAX_PATH - 1, NULL, NULL);

			printf("%s\n", aFileName);

			if (FindData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
			{		
				result += FileNameConvert(filename, CodePage);
			}
			else 
			{
				DWORD BytesWritten = 0;
				/*wchar_t wFileName[MAX_PATH];
				::WriteConsoleW(::GetStdHandle(STD_OUTPUT_HANDLE), wFileName, 
					::MultiByteToWideChar(CodePage, 0, FindData.cFileName, -1, wFileName, MAX_PATH),
					&BytesWritten, NULL);*/

				::WriteConsole(::GetStdHandle(STD_OUTPUT_HANDLE), filename, _tcslen(filename),
					&BytesWritten, NULL);

				printf("\n");
				
				TCHAR filename2[MAX_PATH];
				_tcscpy(filename2, dir);
				_tcscat(filename2, _T("\\"));
				MultiByteToWideChar(936, 0, aFileName, -1, filename2 + _tcslen(filename2), MAX_PATH - 1);

				::CopyFile(filename, filename2, TRUE);

				++result;
			}
		}

		if (!::FindNextFile(hFind, &FindData))
			break;
	}

	::FindClose(hFind);

	return result;
}

int _tmain(int argc, _TCHAR* argv[])
{
	if (argc < 3)
	{
		printf("parameters not enough\n");
		system("pause");
		return 1;
	}

	int count = FileNameConvert(argv[1], _ttoi(argv[2]));

	printf("convert %d files\n", count);

	system("pause");

	return 0;
}

